﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using fmtx.Utility;
using fmtx.webUtility;
using System.Drawing;
using System.Configuration;
using System.Collections;
using System.Text;
using fmtx.Framework.Cache;
using com.fmtx.IDal;
using com.fmtx.Model;
using fmtx.Framework.DALFactory;
using Newtonsoft.Json;
using fmtx.Framework.Model;
using fmtx.Framework.Filter;

public static class StaticCs
{
    #region 大图转缩略图
    /// <summary>
    /// 大图转缩略图
    /// </summary>
    /// <param name="file"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <param name="mode"></param>
    /// <returns></returns>
    public static ImageResult MakeThumbnail(string file, int width, int height, ImageFactory.ImgModel mode)
    {
        ImageResult result = new ImageResult();
        result.FileName = "";
        if (string.IsNullOrEmpty(file))
        {
            return result;
        }
        try
        {
            HttpContext.Current.Server.MapPath(StaticCs.VirtualPath + file);
        }
        catch (Exception)
        {
            file = DownImage(file);
        }
        string filename = Path.GetFileName(file);
        if (string.IsNullOrEmpty(filename)) return result;
        string restleFolder = Path.GetDirectoryName(file);
        string originalImagePath = HttpContext.Current.Server.MapPath(StaticCs.VirtualPath + file);
        string thumbFolder = Path.GetDirectoryName(originalImagePath);
        string ext = Path.GetExtension(originalImagePath);
        string name = filename.Substring(0, filename.LastIndexOf('.'));
        string thumbfilename = name + "_" + width + "x" + height + "_" + mode.ToString() + ext;
        string thumbnailPath = thumbFolder + "/thumb/" + thumbfilename;
        if (!Directory.Exists(thumbFolder + "/thumb/"))
        {
            Directory.CreateDirectory(thumbFolder + "/thumb/");
        }
        if (File.Exists(thumbnailPath))
        {
            using (Image originalImage = Image.FromFile(originalImagePath))
            {
                result.Width = originalImage.Width;
                result.Height = originalImage.Height;
            }
        }
        else
        {
            var res = ImageFactory.MakeThumbnail(originalImagePath, thumbnailPath, width, height, mode);
            result.Height = res.Height;
            result.Width = res.Width;
        }
        result.FileName = restleFolder.Replace(@"\","/") + "/thumb/" + thumbfilename;
        return result;
    } 
    #endregion

    #region 下载网站文件并返回相对路径
    /// <summary>
    /// 下载网站文件并返回相对路径
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    public static string DownImage(string file)
    {
        string folder = HttpContext.Current.Server.MapPath(StaticCs.VirtualPath+"other/");
        if (!Directory.Exists(folder))
        {
            Directory.CreateDirectory(folder);
        }
        return "/other/"+WebHelper.GetFile(file, folder, 200);
    } 
    #endregion

    #region 下载网站文件并返回文件名
    /// <summary>
    /// 下载网站文件并返回文件名
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    public static string DownImageToTemp(string file)
    {
        string folder = HttpContext.Current.Server.MapPath(StaticCs.VirtualPath + LoginModel.User.Uid+"/");
        if (!Directory.Exists(folder))
        {
            Directory.CreateDirectory(folder);
        }
        return  WebHelper.GetFile(file, folder, 200);
    }
    #endregion

    #region 截取图片流
    /// <summary>
    /// 截取图片流
    /// </summary>
    /// <param name="stream"></param>
    /// <param name="path"></param>
    /// <param name="filename"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    public static void SaveAsImg(Stream stream, string path, string filename, int width, int height)
    {
        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
        var res = ImageFactory.MakeThumbnail(stream, width, height, ImageFactory.ImgModel.HeightAndWidth);
        File.WriteAllBytes(path + filename, res.ToArray());
    } 
    #endregion

    #region 删除临时目录
    /// <summary>
    /// 删除临时目录
    /// </summary>
    /// <param name="uid"></param>
    public static void RemoveUserFolder(int uid)
    {
        try
        {
            string path = HttpContext.Current.Server.MapPath(StaticCs.VirtualPath + uid + "/");
            if (Directory.Exists(path)) Directory.Delete(path, true);
        }
        catch (Exception)
        {

        }
    }
    #endregion

    #region 保存临时文件
    /// <summary>
    /// 保存临时文件
    /// </summary>
    /// <param name="filename"></param>
    /// <returns></returns>
    public static string SaveTempPic(string filename)
    {
        if (string.IsNullOrEmpty(filename)) { return ""; }
        string savefilename = "";
        string path = System.Web.HttpContext.Current.Server.MapPath(StaticCs.VirtualPath + LoginModel.User.Uid + "/");
        path = path + filename.Replace("/" + LoginModel.User.Uid,"");
        string mainpath = System.Web.HttpContext.Current.Server.MapPath(StaticCs.VirtualPath);
        string filepath = "/image/" + DateTime.Now.ToString("yyyyMMdd") + "/";
        if (!Directory.Exists(mainpath + filepath))
        {
            Directory.CreateDirectory(mainpath + filepath);
        }
        savefilename = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(filename);
        FileInfo fi = new FileInfo(path);
        if (fi.Length > MaxSizeFile * 1024)
        {
            var bl = (MaxSizeFile * 1024) / fi.Length;
            Image img = Image.FromFile(path);
            int w =(int) (img.Width * bl);
            ImageFactory.MakeThumbnail(path, mainpath + filepath + savefilename, w, 0, ImageFactory.ImgModel.Width);
        }
        else
        {
            fi.CopyTo(mainpath + filepath + savefilename, true);
        }
        return filepath+savefilename;
    }
    #endregion

    #region 保存临时文件
    /// <summary>
    /// 保存临时文件
    /// </summary>
    /// <param name="filename"></param>
    /// <returns></returns>
    public static string SaveTempPic(string filename,int maxlong,ref bool isLong)
    {
        if (string.IsNullOrEmpty(filename)) { return ""; }
        string savefilename = "";
        string path = System.Web.HttpContext.Current.Server.MapPath(StaticCs.VirtualPath + LoginModel.User.Uid + "/" + filename);
        FileInfo fi = new FileInfo(path);
        if (fi.Length > maxlong * 1024)
        {
            isLong = true;
        }
        string mainpath = System.Web.HttpContext.Current.Server.MapPath(StaticCs.VirtualPath);
        string filepath = "/image/" + DateTime.Now.ToString("yyyyMMdd") + "/";
        if (!Directory.Exists(mainpath + filepath))
        {
            Directory.CreateDirectory(mainpath + filepath);
        }
        savefilename = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(filename);
        if (fi.Length > MaxSizeFile * 1024)
        {
            var bl = (MaxSizeFile * 1024) / fi.Length;
            Image img = Image.FromFile(path);
            int w = (int)(img.Width * bl);
            ImageFactory.MakeThumbnail(path, mainpath + filepath + savefilename, w, 0, ImageFactory.ImgModel.Width);
        }
        else
        {
            fi.CopyTo(mainpath + filepath + savefilename, true);
        }
        return filepath + savefilename;
    }
    #endregion

    #region 保存request上传文件
    /// <summary>
    /// 保存request上传文件
    /// </summary>
    /// <param name="filename"></param>
    /// <returns></returns>
    public static string SaveRequestFile(HttpPostedFileBase file)
    {
        string savefilename = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);
        string filefoldr=DateTime.Now.ToString("yyyyMMdd") + "/";
        string path = System.Web.HttpContext.Current.Server.MapPath(StaticCs.VirtualPath + filefoldr);
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        file.SaveAs(path+savefilename);
        return filefoldr + savefilename;
    }
    #endregion

    #region 虚拟路径
    /// <summary>
    /// 虚拟路径
    /// </summary>
    public static string VirtualPath
    {
        get { return ConfigurationManager.AppSettings["VirtualPath"]; }
    } 
    #endregion

    #region 图片网址
    /// <summary>
    /// 图片网址
    /// </summary>
    public static string ImageUrl
    {
        get { return ConfigurationManager.AppSettings["imageurl"]; }
    }
    #endregion

    #region 文件最大值
    /// <summary>
    /// 文件最大值
    /// </summary>
    public static double MaxSizeFile
    {
        get
        {
            var str = ConfigurationManager.AppSettings["maxsizeFile"];
            if (string.IsNullOrEmpty(str))
            {
                return Convert.ToDouble(str);
            }
            return 1024;
        }
    }
    #endregion

    #region 文章中是否加路径
    /// <summary>
    /// 文章中是否加路径
    /// </summary>
    public static bool InsertUrl
    {
        get {
            var str = ConfigurationManager.AppSettings["InsertUrl"];
            if (string.IsNullOrEmpty(str))
            {
                return Convert.ToBoolean(str);
            }
            return false;
        }
    }
    #endregion

    #region 换算时间差
    /// <summary>
    /// 换算时间差
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public static string GetTimer(string data)
    {
        long now = DateTime.Now.Ticks - Convert.ToDateTime(data).Ticks;
        TimeSpan ts = new TimeSpan(now);

        if (ts.Days / (30 * 12) > 0)
        {
            return ts.Days / (30 * 12) + "年";
        }
        else if (ts.Days / 30 > 0)
        {
            return ts.Days / 30 + "月";
        }
        else if (ts.Days > 0)
        {
            return ts.Days + "天";
        }
        else if (ts.Hours > 0)
        {
            return ts.Hours + "小时";
        }
        else if (ts.Minutes > 0)
        {
            return ts.Minutes + "分钟";
        }
        else if (ts.Seconds > 0)
        {
            return ts.Seconds + "秒";
        }
        else
        {
            return "0秒";
        }
    }
    #endregion

    #region 图片属性
    /// <summary>
    /// 图片属性
    /// </summary>
    struct ImageAttr
    {
        public string Src;
        public string Alt;
        public string Width;
        public string Height;
    } 
    #endregion

    #region 将外部文件保存成本地文件
    /// <summary>
    /// 将外部文件保存成本地文件
    /// </summary>
    /// <param name="body"></param>
    /// <param name="firstfile"></param>
    /// <returns></returns>
    public static string SaveHtmlWord(string body, ref string firstfile)
    {
        body = body.Replace("data-original","src");
        List<ImageAttr> imgs = new List<ImageAttr>();
        StringBuilder text = new StringBuilder();
        var imgsss = WebHelper.GetMatchValues("<img(.+?)>", body);
        foreach (var item in imgsss)
        {
            ImageAttr attr = new ImageAttr();
            var gimages = item.GetImages();
            if (gimages.Length > 0)
            {
                attr.Src = gimages[0];
            }

            var galt = item.GetProperty("alt");
            if (galt.Length > 0)
            {
                attr.Alt = galt[0];
            }
            var gwidth = item.GetProperty("width");
            if (gwidth.Length > 0)
            {
                attr.Width = gwidth[0];
            }
            var gheight = item.GetProperty("height");
            if (gheight.Length>0)
            {
                attr.Height = gheight[0];
            }
            imgs.Add(attr);
        }
        var t = WebHelper.Replace(body, @"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", "${img}${img}");
        var bodys = t.Split(new string[] { "${img}$" }, StringSplitOptions.RemoveEmptyEntries);
        int i = 0;

        foreach (var item in bodys)
        {
            if (item.IndexOf("{img}") >= 0 && imgs.Count > 0)
            {
                try
                {
                    if (!WebHelper.HasRegex(StaticCs.ImageUrl + "(.*?)|http://maps.googleapis.com(.*?)", imgs[i].Src) && WebHelper.HasRegex("http://(.*?)|ftp://(.*?)", imgs[i].Src))
                    {
                        string imageurl = "";
                        var temp = DownImageToTemp(imgs[i].Src);
                        bool isLong = false;
                        imageurl = SaveTempPic(temp,600,ref isLong);
                        if (string.IsNullOrEmpty(firstfile))
                        {
                            firstfile = imageurl;
                        }
                        string wandh = string.IsNullOrEmpty(imgs[i].Width) ? "" : "width=" + imgs[i].Width;
                        if (!string.IsNullOrEmpty(imgs[i].Height))
                        {
                            wandh += " height=" + imgs[i].Height;
                        }
                        if (isLong)
                        {
                            text.AppendFormat("<img src='{0}/img?m=MaxWidth&w=800&file={1}' alt=\"{2}\" {3} />",InsertUrl?ImageUrl:"", imageurl, imgs[i].Alt, wandh);
                        }
                        else {
                            text.AppendFormat("<img src='{0}/img/artwork?file={1}' alt=\"{2}\" {3} />", InsertUrl ? ImageUrl : "", imageurl, imgs[i].Alt, wandh);
                        }
                    }
                    else {
                        string wandh = string.IsNullOrEmpty(imgs[i].Width) ? "" : "width=" + imgs[i].Width;
                        if (!string.IsNullOrEmpty(imgs[i].Height))
                        {
                            wandh += " height=" + imgs[i].Height;
                        }
                        var file = imgs[i].Src;
                        if (WebHelper.HasRegex("/img/Temp/(.*?)", file))
                        {
                            var str = WebHelper.GetMatchValues(@"file[?=\\=](.+)", file);
                            if (str.Length > 0)
                            {
                                var temp = str[0].Replace("file=", "");
                                file = SaveTempPic(temp);
                                file = string.Format("{0}/img?m=MaxWidth&w=800&file={1}", InsertUrl ? ImageUrl : "", file);
                            }
                        }
                        if (string.IsNullOrEmpty(firstfile))
                        {
                            var str = WebHelper.GetMatchValues(@"file[?=\\=](.+)", file);
                            if (str.Length > 0)
                            {
                                firstfile = str[0].Replace("file=", "");
                            }
                        }
                        text.AppendFormat("<img src='{0}' alt=\"{1}\" {2} />", file, imgs[i].Alt, wandh);
                    }
                    i++;
                }
                catch (Exception ex)
                {
                    fmtx.Framework.Log.Error(ex);
                }
                text.Append(item);
            }
            else
            {
                text.Append(item);
            }
        }
        return text.ToString().Replace("{img}", "").RemoveUnsafeHtml();
    } 
    #endregion

    #region 过滤地点
    /// <summary>
    /// 过滤地点
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    public static string FileArea(this string text)
    {
        if (string.IsNullOrEmpty(text))
        {
            return string.Empty;
        }
        try
        {
            DataCache cache = new DataCache(CacheKey.FILE_AREA);
            var keys = cache.Get() as List<AreaKey>;
            if (keys == null)
            {
                IPlace _place = DataAccess<IPlace>.GetObject();
                ICity _city = DataAccess<ICity>.GetObject();
                IProvince _province = DataAccess<IProvince>.GetObject();
                ICountry _country = DataAccess<ICountry>.GetObject();
                keys = new List<AreaKey>();
                var plist = _place.QueryIdAndName();
                foreach (var item in plist)
                {
                    if (keys.Where(w=>w.Name==item.Name&&w.Type==AreaType.Place).Count()==0)
                    {
                        keys.Add(new AreaKey(item.Id,item.Name,AreaType.Place,"/place/"+item.Id));
                    }
                }
                var clist = _city.QueryIdAndName();
                foreach (var item in clist)
                {
                    if (keys.Where(w => w.Name == item.Name && w.Type == AreaType.City).Count() == 0)
                    {
                        keys.Add(new AreaKey(item.Id, item.Name, AreaType.City, "/city/" + item.Id));
                    }
                }
                var pplist = _province.QueryIdAndName();
                foreach (var item in pplist)
                {
                    if (keys.Where(w => w.Name == item.Name && w.Type == AreaType.Province).Count() == 0)
                    {
                        keys.Add(new AreaKey(item.Id, item.Name, AreaType.Province, "/Province/" + item.Id));
                    }
                }
                var cclist = _country.QueryIdAndName();
                foreach (var item in cclist)
                {
                    if (keys.Where(w => w.Name == item.Name && w.Type == AreaType.Country).Count() == 0)
                    {
                        keys.Add(new AreaKey(item.Id, item.Name, AreaType.Country, "/country/" + item.Id));
                    }
                }
                if (keys != null && keys.Count != 0)
                {
                    cache.Set(keys, 720);
                }
            }
            FilterDirt kr = new FilterDirt(keys);
            return kr.FilterKeywordsToUrl(text);
        }
        catch (Exception ex)
        {
            fmtx.Framework.Log.Error(ex);
            return text;
        }
    }
    #endregion

    #region 查找地点
    /// <summary>
    /// 过滤地点
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    public static List<AreaKey> FindArea(this string text)
    {
        if (string.IsNullOrEmpty(text))
        {
            return null;
        }
        try
        {
            DataCache cache = new DataCache(CacheKey.FILE_AREA);
            var keys = cache.Get() as List<AreaKey>;
            if (keys == null)
            {
                IPlace _place = DataAccess<IPlace>.GetObject();
                ICity _city = DataAccess<ICity>.GetObject();
                ICountry _country = DataAccess<ICountry>.GetObject();
                IProvince _province = DataAccess<IProvince>.GetObject();
                keys = new List<AreaKey>();
                var plist = _place.QueryIdAndName();
                foreach (var item in plist)
                {
                    if (keys.Where(w=>w.Name==item.Name&&w.Type==AreaType.Place).Count()==0)
                    {
                        keys.Add(new AreaKey(item.Id,item.Name,AreaType.Place,"/place/"+item.Id));
                    }
                }
                var clist = _city.QueryIdAndName();
                foreach (var item in clist)
                {
                    if (keys.Where(w => w.Name == item.Name && w.Type == AreaType.City).Count() == 0)
                    {
                        keys.Add(new AreaKey(item.Id, item.Name, AreaType.City, "/City/" + item.Id));
                    }
                }
                var pplist = _province.QueryIdAndName();
                if (pplist != null)
                {
                    foreach (var item in pplist)
                    {
                        if (keys.Where(w => w.Name == item.Name && w.Type == AreaType.Province).Count() == 0)
                        {
                            keys.Add(new AreaKey(item.Id, item.Name, AreaType.Province, "/Province/" + item.Id));
                        }
                    }
                }
                var tlist = _country.QueryIdAndName();
                foreach (var item in tlist)
                {
                    if (keys.Where(w => w.Name == item.Name && w.Type == AreaType.Country).Count() == 0)
                    {
                        keys.Add(new AreaKey(item.Id, item.Name, AreaType.Country, "/Country/" + item.Id));
                    }
                }

                if (keys != null && keys.Count != 0)
                {
                    cache.Set(keys, 720);
                }
            }
            FilterDirt kr = new FilterDirt(keys);
            return kr.FilterKeyValue(text);
        }
        catch (Exception ex)
        {
            fmtx.Framework.Log.Error(ex);
            return null;
        }
    }
    #endregion

    #region 过滤脏字符
    /// <summary>
    /// 过滤脏字符
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    public static string FileDirt(this string text)
    {
        if (string.IsNullOrEmpty(text))
        {
            return string.Empty;
        }
        try
        {
            DataCache cache = new DataCache(CacheKey.DIRTWORD_TEXT);
            var keys = cache.Get() as List<string>;
            if (keys == null)
            {
                string filename =System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["dirt"]);
                string ss = System.IO.File.ReadAllText(filename, System.Text.Encoding.UTF8);
                keys = ss.Split('|').ToList();
                System.Web.Caching.CacheDependency cd = new System.Web.Caching.CacheDependency(filename);
                cache.Set(keys, 720, cd);
            }
            FilterDirt kr = new FilterDirt(keys);
            return kr.FilterKeywords(text);
        }
        catch (Exception ex)
        {
            fmtx.Framework.Log.Error(ex);
            return text;
        }
    } 
    #endregion

    #region 过滤脏字符
    /// <summary>
    /// 过滤脏字符
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    public static bool IsDirt(this string text)
    {
        try
        {
            DataCache cache = new DataCache(CacheKey.DIRTWORD_TEXT);
            var keys = cache.Get() as List<string>;
            if (keys == null)
            {
                string filename = System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["dirt"]);
                string ss = System.IO.File.ReadAllText(filename, System.Text.Encoding.UTF8);
                keys = ss.Split('|').ToList();
                System.Web.Caching.CacheDependency cd = new System.Web.Caching.CacheDependency(filename);
                cache.Set(keys, 720, cd);
            }
            FilterDirt kr = new FilterDirt(keys);
            return kr.FindAllKeywords(text).Count>0;
        }
        catch (Exception ex)
        {
            fmtx.Framework.Log.Error(ex);
            return false;
        }
    }
    #endregion

    #region 注册名过滤脏字符
    /// <summary>
    /// 注册名过滤脏字符
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    public static bool IsUnameDirt(this string text)
    {
        try
        {
            DataCache cache = new DataCache(CacheKey.DIRTWORD_UNAME);
            var keys = cache.Get() as List<string>;
            if (keys == null)
            {
                string filename = System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["dirtname"]);
                string ss = System.IO.File.ReadAllText(filename, System.Text.Encoding.UTF8);
                keys = ss.Split('|').ToList();
                System.Web.Caching.CacheDependency cd = new System.Web.Caching.CacheDependency(filename);
                cache.Set(keys, 720, cd);
            }
            FilterDirt kr = new FilterDirt(keys);
            return kr.FindAllKeywords(text).Count > 0;
        }
        catch (Exception ex)
        {
            fmtx.Framework.Log.Error(ex);
            return false;
        }
    }
    #endregion

    #region 获取系统关键字
    /// <summary>
    /// 获取系统关键字
    /// </summary>
    /// <returns></returns>
    public static List<string> SysKeywords()
    {
        DataCache cache = new DataCache(CacheKey.DIRTWORD_KEYWORD);
        var keys = cache.Get() as List<string>;
        if (keys == null)
        {
            string filename = System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["keyword"]);
            string ss = System.IO.File.ReadAllText(filename, System.Text.Encoding.UTF8);
            keys = ss.Split('|').ToList();
            System.Web.Caching.CacheDependency cd = new System.Web.Caching.CacheDependency(filename);
            cache.Set(keys, 720, cd);
        }
        return keys;
    } 
    #endregion

    #region 关键字查找
    /// <summary>
    /// 关键字查找
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    public static List<KeywordSearchResult> FilterKeyword(this string text)
    {
        try
        {
            var keys = SysKeywords();
            FilterDirt kr = new FilterDirt(keys);
            return kr.FindAllKeywords(text);
        }
        catch (Exception ex)
        {
            fmtx.Framework.Log.Error(ex);
            return null;
        }
    }
    #endregion

    #region 关键字保存
    /// <summary>
    /// 关键字保存
    /// </summary>
    /// <param name="keyword"></param>
    /// <returns></returns>
    public static string SaveKeyWord(string keyword,Target tag)
    {
        string resstr = "";
        if (!string.IsNullOrEmpty(keyword))
        {
            var res = WebHelper.Replace(keyword, "、|；|;|，|\r\n|\r|\n| ", ",");
            var arry = res.Split(',');
            if (arry != null)
            {
                foreach (var item in arry)
                {
                    if (!string.IsNullOrEmpty(item) && !item.IsDirt() && !resstr.Contains(item))
                    {
                        IKeyWord obj = DataAccess<IKeyWord>.GetObject();
                        obj.IsExists(item,tag);
                        resstr += item+" ";
                    }
                }
            }
            if (resstr.Length > 1)
            {
                resstr=resstr.Remove(resstr.Length - 1);
            }
        }
        return resstr;
    } 
    #endregion

    #region 提取关键字保存
    /// <summary>
    /// 提取关键字保存
    /// </summary>
    /// <param name="keyword"></param>
    /// <returns></returns>
    public static string SaveKeyWord(string html)
    {
        string resstr = "";
        if (!string.IsNullOrEmpty(html))
        {
            var keyres = html.FilterKeyword();
            if (keyres != null)
            {
                for (int i = 0; i < 5&&i<keyres.Count;i++ )
                {
                    var item=keyres[i];
                    if (!string.IsNullOrEmpty(item.Keyword) && !resstr.Contains(item.Keyword))
                    {
                        resstr += item.Keyword + " ";
                    }
                }
            }
            if (resstr.Length > 1)
            {
                resstr = resstr.Remove(resstr.Length - 1);
            }
        }
        return resstr;
    }
    #endregion

    #region 写入文章浏览数
    /// <summary>
    /// 写入文章浏览数
    /// </summary>
    /// <param name="model"></param>
    public static void SetShowArticleCount(int id)
    {
        var has = fmtx.webUtility.WebCookieHelper.GetCookie("Article", "h5$g_1!^");
        List<int> list=null;
        if (!string.IsNullOrEmpty(has))
        {
            list = JsonConvert.DeserializeObject<List<int>>(has);
        }
        if (list == null)
        {
            list = new List<int>();
        }
        if (!list.Contains(id))
        {
            IArticle article = fmtx.Framework.DALFactory.DataAccess<IArticle>.GetObject();
            Article model = article.Get(id);
            model.ShowCount++;
            article.Update(model);
            list.Add(model.Id);
            fmtx.webUtility.WebCookieHelper.SetCookie("Article", "h5$g_1!^", JsonConvert.SerializeObject(list), 360);
        }
    } 
    #endregion

    #region 写入图片浏览数
    /// <summary>
    /// 写入图片浏览数
    /// </summary>
    /// <param name="model"></param>
    public static void SetShowPictureCount(int id)
    {
        var has = fmtx.webUtility.WebCookieHelper.GetCookie("Picture", "h5$g_1!^");
        List<int> list = null;
        if (!string.IsNullOrEmpty(has))
        {
            list = JsonConvert.DeserializeObject<List<int>>(has);
        }
        if (list == null)
        {
            list = new List<int>();
        }
        if (!list.Contains(id))
        {
            IPicture picture = fmtx.Framework.DALFactory.DataAccess<IPicture>.GetObject();
            var model = picture.Get(id);
            model.ShowCount++;
            picture.Update(model);
            list.Add(model.Id);
            fmtx.webUtility.WebCookieHelper.SetCookie("Picture", "h5$g_1!^", JsonConvert.SerializeObject(list), 360);
        }
    }
    #endregion

    #region 替换alt，title，图片绝对路径
    /// <summary>
    /// 替换alt，title，图片绝对路径
    /// </summary>
    /// <param name="txt"></param>
    /// <returns></returns>
    public static string FileImgOrUrl(this string txt)
    {
        //var pattern = @"alt=['|""]<a(.*?)>(.*?)</[\s\t\r\n]*a[\s\t\r\n]*>(.*?)['|""]|title=['|""]<a(.*?)>(.*?)</[\s\t\r\n]*a[\s\t\r\n]*>(.*?)['|""]";
        //var onelist = WebHelper.GetMatchValues(pattern, txt);
        //foreach (var item in onelist)
        //{
        //    txt = txt.Replace(item, WebHelper.Replace(item, @"<.*?>", ""));
        //}
        txt = WebHelper.Replace(txt, @"/img(.*?)", StaticCs.ImageUrl + "/img");
        return txt;
    } 
    #endregion

    #region 转换为页项数
    /// <summary>
    /// 转换为页项数
    /// </summary>
    /// <param name="count"></param>
    /// <param name="size"></param>
    /// <returns></returns>
    public static int GetCuSize(int count, int size)
    {
        if (count < size)
        {
            return 1;
        }
        if (count % size == 0)
        {
            return count / size;
        }
        else
        {
            return (count / size) + 1;
        }
    } 
    #endregion
}